package com.wh.minio.container.dao;


import com.wh.minio.container.common.DateTool;
import com.wh.minio.container.common.MinioClientUtils;
import com.wh.minio.container.dto.BucketDTO;
import io.minio.MinioClient;
import io.minio.Result;
import io.minio.errors.MinioException;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/***
 * BucketDao, minio的桶DAO
 * @Package com.wh.minio.container.dao
 * @author 谢泽鹏
 * @date 2016年11月07日 下午15:10
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 * @version V1.0
 */
public class BucketDao {


    /**
     *
     * @return
     * @throws MinioException
     * @throws NoSuchAlgorithmException
     * @throws IOException
     * @throws InvalidKeyException
     * @throws XmlPullParserException
     */
    public List<BucketDTO> listBuckets() throws MinioException, NoSuchAlgorithmException, IOException,
            InvalidKeyException, XmlPullParserException {
        List<BucketDTO> bucketDTOS = new ArrayList<>();
        MinioClient minioClient = MinioClientUtils.getInstance().getMinioClient();
        List<Bucket> buckets = minioClient.listBuckets();
        for (Bucket bucket : buckets) {
            BucketDTO bucketDTO = new BucketDTO();
            bucketDTO.setBucketName(bucket.name());
            Iterable<Result<Item>> myObjects = minioClient.listObjects(bucket.name());
            List<com.wh.minio.container.entity.Bucket> resource = new ArrayList<>();
            for (Result<Item> result : myObjects) {
                Item item = result.get();
                com.wh.minio.container.entity.Bucket bucketRes = new com.wh.minio.container.entity.Bucket();
                bucketRes.setObjectName(item.objectName());
                bucketRes.setObjectSize(item.objectSize());
                bucketRes.setLastModified(DateTool.format(item.lastModified(), "yyyy-MM-dd HH:mm:ss"));
                bucketRes.setEtag(item.etag().replace("\"","") );
                bucketRes.setDir(item.isDir());
                bucketRes.setStorageClass(item.storageClass());
                bucketRes.setOwnerId(item.owner().id());
                bucketRes.setOwnerDisplayName(item.owner().displayName());
                bucketRes.setUrl(minioClient.presignedGetObject(bucket.name(), item.objectName()));
                bucketRes.setObjectUrl(minioClient.getObjectUrl(bucket.name(), item.objectName()));
                resource.add(bucketRes);
            }
            bucketDTO.setResource(resource);
            bucketDTOS.add(bucketDTO);
        }
        return bucketDTOS;
    }


}
